﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace contact
{
    public partial class capcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string[] fonts = { "Arial Black”, “Lucida Sans Unicode”, “Comic Sans MS" };
            const byte LENGTH = 5;
            // Random string
            const string chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            using (Bitmap bmp = new Bitmap(120, 30))
            {
                using (Graphics g = Graphics.FromImage(bmp))
                {
                    // Create background image
                    HatchBrush brush = new HatchBrush(HatchStyle.Wave, Color.White, Color.Wheat);
                    g.FillRegion(brush, g.Clip);
                    // Save string random
                    StringBuilder strCaptcha = new StringBuilder();
                    Random rand = new Random();
                    for (int i = 0; i < LENGTH; i++)
                    {
                        // Get random string from array
                        string str = chars[rand.Next(chars.Length)].ToString();
                        strCaptcha.Append(str);
                        // Craete font
                        Font font = new Font(fonts[rand.Next(fonts.Length)], 12, FontStyle.Strikeout | FontStyle.Italic);
                        // Get size string
                        SizeF size = g.MeasureString(str, font);
                        // Draw string on image
                        g.DrawString(str, font,
                        Brushes.Chocolate, i * size.Width + 3, rand.Next(2, 10));
                        font.Dispose();
                    }
                    // Save captcha in session
                    Session["captcha"] = strCaptcha.ToString();
                    // Export to gif format
                    Response.ContentType = "image/GIF";
                    bmp.Save(Response.OutputStream, ImageFormat.Gif);
                }
            }
        }
    }
}